<template>
  <view class="hypage">
    <!-- 地址列表 -->
    <view class="address-list">
      <view v-for="address in addresses" :key="address.id" class="address-item">
        <view class="info">
          <text class="name">{{ address.name }}</text>
          <text class="phone">{{ address.phone }}</text>
          <text class="default-tag" v-if="address.isDefault">默认</text>
        </view>
        <view class="detail">
          {{ address.detail }}
        </view>
        <view class="actions">
          <view class="actions-left">
            <label class="checkbox-label" v-if="active_id" @click="selectAddress(address.id)">
              <checkbox
                :checked="address.id == active_id"
                color="#409eff"
                @click.stop="selectAddress(address.id)"
              />
              选择
            </label>
            <text
              v-if="address.isDefault == false && !active_id"
              @click.stop="setDefault(address.id)"
              >设为默认</text
            >
          </view>
          <view class="actions-right">
            <text @click.stop="editAddress(address.id)">编辑</text>
            <text class="del" @click.stop="deleteAddress(address.id)"
              >删除</text
            >
          </view>
        </view>
      </view>

      <!-- 没有地址时提示 -->
      <view v-if="addresses.length == 0" class="no-address">
        <hy-null :msg="'没有收货地址'" />
      </view>
    </view>

    <!-- 添加地址按钮 -->
    <view class="add-button">
      <button @click="addNewAddress">新增地址</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import {
  fetchAddressListApi,
  setDefaultAddressApi,
  deleteAddressAPI,
} from "@/api/address";
import HyNull from "@/components/HyNull.vue";
import { userStore } from "@/stores/modules/userStore";
import { showError, showSuccess, showWarning } from "@/utils/feedback";
const user = userStore();

// 地址列表
const addresses = ref([]);

// 当前选中的地址ID
const active_id = ref("");

// 卡券ID（从路由传参获取）
let card_id = ref("");

// 获取地址列表
const getAddressList = async () => {
  try {
    const res = await fetchAddressListApi();
    if (res.code == 200) {
      addresses.value = res.data;
    } else {
      showError(res.message);
    }
  } catch (error) {
    showError(res.message);
    console.error("获取地址失败:", error);
  }
};

// 页面加载生命周期
onLoad((options) => {
  card_id.value = options.card_id;
  getAddressList();
  if (card_id.value) {    
    active_id.value = user.userInfo.shopAddressId;
  }
});

/**
 * 选择地址并返回卡卷兑换页面
 * @param {Number} id - 地址ID
 */
const selectAddress = (id) => {
  if (card_id.value) {
    active_id.value = id;
    user.setAddress(id);
    uni.navigateTo({ url: `/pages/card/detail?card_id=${card_id.value}` });
  }
};

/**
 * 新增地址
 */
const addNewAddress = () => {
  uni.navigateTo({ url: `/pages/address/edit?card_id=${card_id.value}` });
};

/**
 * 编辑地址
 * @param {Number} id - 地址ID
 */
const editAddress = (id) => {
  uni.navigateTo({ url: `/pages/address/edit?id=${id}&card_id=${card_id.value}` });
};

/**
 * 删除地址
 * @param {Number} id - 地址ID
 */
const deleteAddress = async (id) => {
  const success = await showConfirmModal("确定要删除该地址吗？", async () => {
    try {
      const response = await deleteAddressAPI(id);
      if (response.code == 200) {
        showSuccess("删除成功");
        return true;
      } else {
        showError(response.message);
        return false;
      }
    } catch (error) {
      showError("删除失败，请重试");
      console.error("删除地址失败：", error);
      return false;
    }
  });

  if (success) {
    await getAddressList();
  }
};

/**
 * 设为默认地址
 * @param {Number} id - 地址ID
 */
const setDefault = async (id) => {
  const success = await showConfirmModal("确定要设为默认地址吗？", async () => {
    try {
      const response = await setDefaultAddressApi(id);
      if (response.code == 200) {
        showSuccess("设置成功");
        return true;
      } else {
        showError(response.message);
        return false;
      }
    } catch (error) {
      showError(error.message || "设置失败");
      console.error("设置默认地址失败：", error);
      return false;
    }
  });

  if (success) {
    await getAddressList();
  }
};

/**
 * 显示确认弹窗并执行操作
 * @param {String} content - 弹窗内容
 * @param {Function} callback - 成功后的回调
 */
const showConfirmModal = (content, callback) => {
  return new Promise((resolve) => {
    uni.showModal({
      title: "提示",
      content,
      success: async (res) => {
        if (res.confirm) {
          const result = await callback();
          resolve(result);
        } else {
          resolve(false);
        }
      },
    });
  });
};
</script>

<style scoped lang="scss">
.hypage {
  padding: 20px;
  padding-bottom: 80px;
}

.address-item {
  background-color: #fff;
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 10px;
  &.active {
    border: 1px solid $uni-color-primary;
  }

  .info {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .name {
      font-size: 16px;
      font-weight: bold;
      margin-right: 10px;
    }

    .phone {
      font-size: 14px;
      color: #666;
      margin-right: 10px;
    }

    .default-tag {
      font-size: 12px;
      color: #ffffff;
      background-color: #f37b1d;
      padding: 2px 6px;
      border-radius: 4px;
    }
  }

  .detail {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
  }

  .actions {
    display: flex;
    font-size: 14px;
    justify-content: space-between;

    text {
      cursor: pointer;
    }
    .actions-left {
      color: #333;
    }
    .actions-right {
      color: #f37b1d;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      .del {
        color: red;
      }
    }
  }
}

.no-address {
  text-align: center;
  color: #999;
  margin-top: 50px;
}

.add-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  button {
    background-color: $color-primary;
    color: #fff;
  }
}
</style>
